import React, { useRef, useEffect, useState } from 'react';
import Plyr from 'plyr';
import 'plyr/dist/plyr.css';
import Hls from 'hls.js';
import { Button } from 'antd';
import axios from 'axios';

const App = () => {
    const videoRef = useRef(null);
    const [isPlaying, setIsPlaying] = useState(false);
    const [isLoading, setIsLoading] = useState(false);

    // 总数量
    const total = useRef(0);
    // 视频ID
    const [num, setNum] = useState(2);
    useEffect(() => {
        axios.get(`http://localhost:3001/api/video-folder-count`).then((res) => {
            total.current = res.data.count;
        }).catch((err) => {
            console.log(err);
        })
    }, [])
    useEffect(() => {
        const player = new Plyr(videoRef.current, {
            controls: ['play-large', 'play', 'progress', 'current-time', 'duration', 'mute', 'volume', 'settings', 'pip', 'fullscreen'],
            settings: ['captions', 'quality', 'speed', 'loop'],
            i18n: {
                speed: '速度',
                normal: '正常',
                quality: '画质',
                loop: '循环',
                rewind: '快退 {seektime}s',
                forward: '快进 {seektime}s',
                seek: '跳转',
                seekLabel: '{currentTime} of {duration}',
                played: '播放了',
                buffered: '缓存',
                currentTime: '当前时间',
                duration: '时长',
                volume: '音量',
                mute: '静音',
                unmute: '取消静音',
                enableCaptions: '启用字幕',
                disableCaptions: '禁用字幕',
                enterFullscreen: '进入全屏',
                exitFullscreen: '退出全屏',
                frameTitle: 'Player for {title}',
                captions: '字幕',
                settings: '设置',
                menuBack: '返回',
                speedLabel: '倍速'
            }
        });

        player.on('play', () => {
            console.log('play');
        })
    }, []);


    useEffect(() => {
        const video = videoRef.current;
        try {
            // 检查 HLS 是否支持
            if (Hls.isSupported() && video) {
                const hls = new Hls();

                // 使用后端提供的 HLS 资源 num为视频ID
                hls.loadSource(`http://localhost:3001/video/video${num}/playlist.m3u8`);
                hls.attachMedia(video);

                hls.on(Hls.Events.MANIFEST_PARSED, () => {
                    setIsLoading(false);
                    if (isPlaying) {
                        video.play();
                    }
                });

                hls.on(Hls.Events.ERROR, (event, data) => {
                    console.error('HLS error:', data);
                    setIsLoading(false);
                });

                return () => {
                    hls.destroy();
                };
            } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
                // 对于 iOS 设备的 HLS 原生支持
                video.src = 'http://localhost:3001/video/playlist.m3u8';
                video.addEventListener('loadedmetadata', () => {
                    setIsLoading(false);
                    if (isPlaying) {
                        video.play();
                    }
                });
            }
        } catch (err) {
            console.log(err, '>>>>');
        }

    }, [num])





    const handlePlayClick = () => {
        setIsPlaying(true);
        setIsLoading(true);
        videoRef.current.play();
    };

    // 播放结束后处理
    const handleEnded = () => {
        setIsPlaying(false);
    };

    return (
        <div>
            <div style={{ width: '800px' }} className='mutation-box'>
                <video
                    ref={videoRef}
                    width={500}
                    id='play'
                    onEnded={handleEnded}
                    controls
                />
                {!isPlaying && !isLoading && (
                    <button onClick={handlePlayClick} style={{ marginTop: '10px' }}>
                        Play Video
                    </button>
                )}
                {isLoading && <p>Loading...</p>} {/* 加载指示 */}
            </div>
            <Button onClick={() => setNum(e => e - 1 <= 0 ? 1 : e - 1)}>上一个</Button>
            <Button onClick={() => setNum(e => e + 1 > total.current ? total.current : e + 1)}>下一个</Button>
        </div>
    );
};

export default App;
